package com.itheima.tanhua.api;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.intern.InternUtil;
import cn.hutool.core.util.ObjectUtil;
import com.itheima.tanhua.api.mongo.MovementServiceApi;
import com.itheima.tanhua.util.IdWorker;
import com.itheima.tanhuan.CommentType;
import com.itheima.tanhuan.pojo.db.Friend;
import com.itheima.tanhuan.pojo.mongo.*;

import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;


import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;

@DubboService
public class MovementServiceApiImpl implements MovementServiceApi {
    @Autowired
    IdWorker idWorker;
    @Autowired
    MongoTemplate mongoTemplate;

    //发布动态
    @Override
    public Boolean publish(Movement movement) {
        //保存动态发布
        movement.setPid(idWorker.getNextId("movement"));
        Movement save = mongoTemplate.save(movement);
        //查询用户的朋友id
        List<Friend> friendList = mongoTemplate.find(Query.query(Criteria.where("userId").is(movement.getUserId())), Friend.class);
        System.out.println(friendList);
        //3、循环好友数据，构建时间线数据存入数据库
        for (Friend friend : friendList) {
            MovementTimeLine movementTimeLine = new MovementTimeLine();
            movementTimeLine.setMovementId(save.getId());
            movementTimeLine.setUserId(movement.getUserId());
            movementTimeLine.setFriendId(friend.getFriendId());
            movementTimeLine.setCreated(movement.getCreated());
            System.out.println(mongoTemplate.findAll(MovementTimeLine.class));
            MovementTimeLine save1 = mongoTemplate.save(movementTimeLine);
            System.out.println(save1);
        }

        return true;
    }

    //根据uid查登陆者
    @Override
    public List<Friend> friendById(Long userId) {
        //根据用户id查找盆友
        List<Friend> friendList = mongoTemplate.find(Query.query(Criteria.where("userId").is(userId)), Friend.class);

        return friendList;
    }

    @Override
    public List<Movement> getMove(Long fid, Integer page, Integer pagesize) {
        //查询动态
        List<Movement> fmove = mongoTemplate.find(Query.query(Criteria.where("userId").is(fid))
                .skip((Convert.toLong(page) - 1) * pagesize)
                .limit(pagesize), Movement.class);
        return fmove;
    }

    @Override
    public List<Movement> getFriend(String friendid, int page, int pagesize) {
        //朋友的ids集合
        Query query = Query.query(Criteria.where("friendId").is(Convert.toLong(friendid)));
//                skip((page-1)*pagesize).
//                limit(pagesize).with(Sort.by(Sort.Order.desc("created")));
        List<MovementTimeLine> movementTimeLines = mongoTemplate.find(query, MovementTimeLine.class);
        //获得ids
        List<ObjectId> userIds = CollUtil.getFieldValues(movementTimeLines, "movementId", ObjectId.class);
        //得到对应的动态
        Query query1 = Query.query(Criteria.where("id").in(userIds));
        List<Movement> movements = mongoTemplate.find(query1, Movement.class);
//        return new ArrayList<Movement>();
        return movements;
    }

    //根据动态id查询
    @Override
    public Movement getmoveById(ObjectId id) {
        Movement movement = mongoTemplate.findById(id, Movement.class);
        return movement;
    }

    //推荐动态
    @Override
    public List<Movement> findRecommendMovements(List<Long> split) {
        Query query = Query.query(Criteria.where("pid").in(split));
        List<Movement> movements = mongoTemplate.find(query, Movement.class);
        return movements;
    }

    //随机推荐
    @Override
    public List<Movement> randomCount(int count) {
        TypedAggregation aggregation = Aggregation.newAggregation(Movement.class,
                Aggregation.sample(count));
        AggregationResults<Movement> movements = mongoTemplate.aggregate(aggregation, Movement.class);
        return movements.getMappedResults();
    }
//动态喜欢数+1
    @Override
    public Integer likeComment(ObjectId movementId) {
        Movement mongoTemplateById = mongoTemplate.findById(movementId, Movement.class);
        Query query = Query.query(Criteria.where("id"));
        List<Movement> movements = mongoTemplate.find(query, Movement.class);


        Integer likeCount = mongoTemplateById.getLikeCount();
        if (ObjectUtil.isEmpty(likeCount)||likeCount<0){
            likeCount=0;
        }
        Update update = new Update();
        update.set("likeCount", likeCount+1);
        mongoTemplate.updateFirst(query,update,Movement.class);
        return likeCount+1;
    }

    @Override
    public Integer decreaseLikeMove(String movementId) {
        Movement mongoTemplateById = mongoTemplate.findById(new ObjectId(movementId), Movement.class);
        Query query = Query.query(Criteria.where("id"));
        Integer likeCount = mongoTemplateById.getLikeCount();
        if (ObjectUtil.isEmpty(likeCount)||likeCount<1){
            likeCount=1;
        }
        Update update = new Update();
        update.set("likeCount", likeCount-1);
        mongoTemplate.updateFirst(query,update,Movement.class);
        return likeCount-1;
    }
/*//判断有没有来访者
    @Override
    public Boolean isvisitor(Long visitor, Long userId) {
        return mongoTemplate.exists(Query.query(Criteria.where("userId").is(userId)
                .and("visitorUserId").is(visitor)), Visitors.class);
    }
//游客和用户的缘分值
    @Override
    public Integer haveScore(Visitors visitors, Long userId) {
        RecommendUser one = mongoTemplate.findOne(Query.query(
                Criteria.where("toUserId").is(visitors)
                        .and("userId").is(userId)
        ), RecommendUser.class);
        Integer integer1 = Convert.toInt(one.getScore());

        if (ObjectUtil.isEmpty(integer1)){
            return 60;
        }
        return integer1;
    }
//保存数据
    @Override
    public void saveVisitor(Visitors visitors) {
        mongoTemplate.save(visitors);
    }*/

}
